<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="86px">
      <el-form-item label="患者姓名" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入患者姓名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="血片编号" prop="sliceNo">
        <el-input v-model="queryParams.sliceNo" placeholder="请输入血片编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="报告单ID号" prop="serialNo">
        <el-input v-model="queryParams.serialNo" placeholder="请输入报告单ID号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择创建日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8" id="btn">
      <el-col :span="1.5">
        <el-button type="primary"  plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['his:patient:mda']" >新增</el-button>
      </el-col>
    </el-row>-->

    <el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" align="center" :index="indexMethod" label="序号"></el-table-column>
      <el-table-column label="血片编号" align="center" prop="sliceNo"/>
      <el-table-column label="实验室编号" align="center" prop="sampleName" width="190" />

      <el-table-column label="姓名" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <router-link :to="'/his/reg_treat/mda_edit/' + scope.row.id" class="link-type">
            <span>{{ scope.row.patientName }}</span>
          </router-link>
        </template>
        <router-view :key="$route.fullPath" />
      </el-table-column>
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.his_doctor_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" width="70"/>
<!--      <el-table-column label="联系电话" align="center" prop="tel" />-->
      <el-table-column label="报告单ID号" align="center" prop="serialNo"/>
      <el-table-column label="检测项目" align="center" prop="subscreening" width="226px"/>
      <el-table-column label="门诊号" align="center" prop="outpatient"/>
      <el-table-column label="丙二醛" align="center" prop="mda">
        <template slot-scope="scope">
          <div v-if="scope.row.mda!=null">
          <el-tooltip class="item" effect="light" :content="scope.row.sampleType" placement="right">
<!--             <span>{{scope.row.mda}}</span>-->
            <router-link :to="'/his/reg_treat/mda_edit/' + scope.row.id" class="custom-link">{{scope.row.mda}}</router-link>
          </el-tooltip>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="录入时间" align="center" prop="createTime" width="156px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"width="129px" >
        <template slot-scope="scope">
          <router-link :to="'/his/reg_treat/mda_edit/' + scope.row.id"><el-button type="text" icon="el-icon-edit">查看</el-button></router-link>
<!--          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['his:patient:mda_remove']">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改患者对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">

<!--        <el-row id="left_row">
          <el-col :span="14">
              <el-form-item label="血片编号" prop="sliceNo">
                <el-input v-model="form.sliceNo" placeholder="" clearable/>
              </el-form-item>
          </el-col>
&lt;!&ndash;          <el-col :span="10" id="left_col">
            <el-form-item >
              <el-button type="primary" plain icon="el-icon-plus" @click="handleAddBpn" style="margin-left: 10px">选择血片编号</el-button>
             &lt;!&ndash; <el-autocomplete
                               placeholder="请输入搜索的血片编号"
                               v-model="form.sliceNo"
                               :fetch-suggestions="querySearch"
                               :trigger-on-focus="false"
                               @select="handleSelect"
                               prefix-icon="el-icon-search"
                               class="input-with-select"
              >
              </el-autocomplete>&ndash;&gt;
            </el-form-item>
          </el-col>&ndash;&gt;
        </el-row>-->

        <el-form-item label="血片编号" prop="sliceNo">
          <el-input v-model="form.sliceNo" placeholder="" clearable/>
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别" clearable>
            <el-option v-for="dict in dict.type.his_doctor_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="化验单ID号" prop="remark">
          <el-input v-model="form.serialNo" placeholder="请输入化验单ID号" />
        </el-form-item>

        <el-form-item label="患者电话" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入患者电话" />
        </el-form-item>
        <el-form-item label="患者年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入患者年龄" />
        </el-form-item>
        <el-form-item label="常住地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址信息" />
        </el-form-item>
        <el-form-item label="过敏史" prop="allergy">
          <el-input v-model="form.allergy" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="门诊号" prop="outpatient">
          <el-input v-model="form.outpatient" placeholder="请输入门诊号/住院号" />
        </el-form-item>
        <el-form-item label="检测机构" prop="unit">
          <el-input v-model="deptName" placeholder="请输入所属机构" disabled/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--绑定血片编号-->
    <el-dialog :title="bpnTitle" :visible.sync="bpnOpen" width="900px" append-to-body>
      <BpnComponet :value.sync="deptId" ref="childselected" v-on:formSubmit='translateText'></BpnComponet>
    </el-dialog>


  </div>

</template>
<style>

.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 100px;
  color: #ddaf38;
}
.table-expand .el-form-item {
  margin-left: 824px;
  margin-bottom: 0;
}
#left_col .el-form-item__content{
  margin-left: 42px !important;
}

 #btn .el-button--info.is-plain{
   color: #719df5;
   background: #f2f2fd;
   border-color: #d3d4d6;
 }
#btn .el-button--info.is-plain:hover, .el-button--info.is-plain:focus {
  background: #909399;
  border-color: #909399;
  color: #FFFFFF;
}
.custom-link {
  color: #333; /* 默认文本颜色 */
}

.custom-link:hover {
  color: red; /* 鼠标放上时的文本颜色 */
}
</style>

<script>
import { listMdaPatient, delPatient, addPatient} from '@/api/his/mda'
import { addMdaAttribute} from '@/api/his/attribute'
import { getUserProfile } from '@/api/system/user'
import { addBpn, listBpns } from '@/api/his/bpn'
import BpnComponet from '../components/BpnComponent'

export default {
  dicts: [
    'his_doctor_sex',
    'his_screening_status',
    'his_screening_calculate',
    'his_risk_type',
    'his_saas_type',
    'his_screening_unit',
    'his_bpn_status'
  ],
  name: "Mda",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者表格数据
      patientList: [],
      // 弹出层标题
      title: "",
      bpnTitle:"",
      // 是否显示弹出层
      open: false,
      bpnOpen:false,
      process: false,
      calculation: false,
      fdisabled:false,
      tableData:[],
      // 查询参数
      queryParams: {
        delFlag: 0,
        screeningType:'脂质过氧化特殊染色检测',
        subscreening:'脂质过氧化特殊染色检测',
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        screening:null,
        tel: null,
        idCard: null,
        age: null,
        gender: null,
        address: null,
        patientDate: null,
        createTime: null,
        inputValue:null
      },
      deptId:null,
      deptName:null,
      // 表单参数
      form: {
        sliceNo:'',
      },
      bpns:[],
      // 表单校验
      rules: {
        patientName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        tel: [
          { required: false, message: "电话不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        sliceNo: [
          { required: true, message: "血片编号不能为空", trigger: "input" }
        ],
      },
    };
  },
  watch: {
    '$route': function () {
      this.getList()
    }
  },
  created() {
    this.getList();
    this.getUser();
  },
  methods: {
    // 生成表头序号
    indexMethod(index) {
      this.queryParams.pageNum <= 0 ? this.queryParams.pageNum = 1 : this.queryParams.pageNum
      if(this.queryParams.pageNum != 1) {
        return index + 1 + ((this.queryParams.pageNum - 1) * this.queryParams.pageSize)
      }
      // 否则直接返回索引+1作为序号
      return index + 1
    },

    getBpnList(){
      //status:3 设备已上传mda
      this.tableData.length = 0;
      let param = {deptId:this.queryParams.deptId ,status:0,delFlag:0} //status:0 未使用
      listBpns(param).then(response => {
        response.forEach((self) => {
          if(!this.tableData.includes(self.id)){
            this.tableData.push({id:self.id, bpnName:self.bpnName})
          }
        });
      });
    },

    // 当queryString不为空的时候，就把输⼊的内容在数据库中做对⽐，如果有能够模糊关联的，就直接取出
    // 并返回给带搜索建议的输⼊框，输⼊框就把返回的数据以下拉框的形式呈现出来
    async querySearch(queryString, cb) {

      if (queryString !== "") {
        //不用setTimeout，用async/await
        //发请求
        this.inputValue = queryString;
        //await this.getList();

        //准备⼀个空数组，此数组是最终返给输⼊框的数组
        let callBackArr = [{number: '', value: ""}];
        this.tableData.forEach((item) => {
          // 把数据库做遍历，拿⽤户输⼊的这个字，和数据库中的每⼀项做对⽐
          if (item.bpnName.indexOf(queryString) > -1) {
            // ⼤于-1，只要包含就⾏，不再乎位置,如果有具有关联性的数据,就存到callBackArr⾥⾯准备返回呈现
            callBackArr.push({number: `${item.id}`, value: `${item.bpnName}`});
          }
        });
        //如果这个数组还为空，说明没有查询到具有关联的数据，就直接返回暂⽆数据
        if (callBackArr.length === 0) {
          cb([{value: "暂⽆数据", price: "暂⽆数据"}]);
        } else {
          // 如果经过查询操作以后，找到数据了，就把装有关联数据的数组callBackArr进行呈现
          cb(callBackArr);
        }
      }
    },
    // 点击谁，就把谁放进去
    handleSelect(item) {
      this.tableData.bpnName = item.value;
      this.form.sliceNo = item.value;
    },

    /** 查询患者列表 */
    getList() {
      this.loading = true;
      listMdaPatient(this.queryParams).then(response => {
        //console.log('response: ',JSON.stringify(response))
        this.patientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = this.process = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        //patientId: null,
        patientName: null,
        sliceNo:null,
      };
      this.resetForm("form");
      this.queryParams.inputValue=null

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.queryParams.screening!=null){
        this.queryParams.screeningItem = this.queryParams.screening[0];
        this.queryParams.riskWarning = this.queryParams.screening[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getBpnList();
      this.open = true;
      this.title = "添加患者";
    },
    handleAddBpn(){
      this.bpnOpen = true;
      this.bpnTitle = '绑定血片编号'
    },
    translateText(obj){
      this.bpnOpen = false;
      if(obj!=undefined){
        this.form.sliceNo = obj.bpnName;
      }
      //重新加载列表
      this.$refs.childselected.getList();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({ path: '/his/reg_treat/mda_edit', query: { id: row.patientId }})
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.bpns = selection.map(item => item.sliceNo+'-'+item.status)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          /* if (this.form.patientId != null) {
            updatePatient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }); */
          //} else {
            this.form.screeningType = '脂质过氧化特殊染色检测';
            this.form.subscreening = '脂质过氧化特殊染色检测';
            this.form.status = 0;
            //查询血片编号是否已导入
            var formBpn = {
              deptId: this.deptId,
              bpnName: this.form.sliceNo,
              status: '1',
              createBy:'admin',
              createTime: Date.now(),
              updateTime: Date.now()
            }
            //listBpn(formBpn).then(response => {
                //if(response.rows.length>0){
                  //var id = response.rows[0].id;
                  addPatient(this.form).then(response => {
                    var patientId = response.data;
                    var attribute = { patientId: patientId, sliceNo: this.form.sliceNo, addTime: Date.now() }
                    addMdaAttribute(attribute).then(response => {
                      console.log(response,response)
                      //var bpns = [this.form.sliceNo + '-' + 1]; //更新血片状态1
                      addBpn(formBpn).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                        this.reset();
                      });
                    })
                  });
                //}else{
                //  this.$modal.msgError("血片编号不存在")
                //}
                this.tableData.length = 0;
              //}).catch(() => {
              //this.$modal.msgError("新增失败")
            //});

        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
        return delPatient(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleCancel: function() {
      this.process = false;
      this.calculation = false;
      this.$router.push({ path: '/patient'})
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('his/patient/export', {
        ...this.queryParams
      }, `patient_${new Date().getTime()}.xlsx`)
    },

    getUser() {
      getUserProfile().then(response => {
        this.deptName = response.data.dept.deptName;
        this.deptId = response.data.dept.deptId;
      })
    }
  },

  components:{
    BpnComponet
  }
};
</script>
